<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-08-08
 * Time: 10:34
 */

namespace App\Repositories;


use Spatie\Permission\Models\Role;

/**
 * 遵循SOLID原则（分割、单元测试、mock测试）
 * 基于Role和Spatie\Permission\Models\Role model的数据库逻辑
 * Class RoleRepository
 * @package App\Repositories
 */
class RoleRepository
{
    /**
     * @var Role 注入的Role model
     */
    protected $role;

    /**
     * RoleRepository constructor.
     * @param Role $role
     */
    public function __construct(Role $role){
        $this->role = $role;
    }

    /**
     * 返回角色列表
     * @param $name
     * @param $limit
     * @return mixed
     */
    public function getRolePages($name, $limit){
        return $this->role
            ->when($name, function ($query) use ($name){
                $query->where('name', 'like', '%'.$name.'%');
            })
            ->orderByDesc('created_at', 'updated_at')
            ->paginate($limit);

    }

    /**
     * 新增保存角色
     * @param array $data
     * @return Role
     */
    public function postRole(array $data){
        $this->role->name = $data['name'];
        $this->role->description = data_get($data, 'description');
        $this->role->guard_name = data_get($data, 'guard_name', 'api');

        $this->role->saveOrFail();

        return $this->role;
    }

    /**
     * 修改保存角色
     * @param array $data
     * @return mixed
     */
    public function updateRole(array $data){

        $role = $this->role->findOrFail($data['id']);

        $role->name = $data['name'];
        $role->description = data_get($data, 'description');

        $role->saveOrFail();
        
        return $role;
    }

    /**
     * 根据角色名称获取角色id
     * @param $name
     * @return mixed
     */
    public function getRoleIdByName($name){
        return $this->role->where('name', $name)->value('id');
    }

    /**
     * 返回单条角色数据
     * @param int $id
     * @return mixed
     */
    public function getSingleRole(int $id){
        return $this->role->findOrFail($id);
    }

    /**
     * 返回所有列表
     * @return mixed
     */
    public function getRoleList(){
        return  $this->role->get(['id', 'name']);
    }

    /**
     * 删除角色
     * @param array $ids
     * @return int
     */
    public function deleteRole(array $ids){
        return $this->role->destroy($ids);
    }

    /**
     * 获取所有数据
     * @param array $ids
     * @return mixed
     */
    public function getAllRoleListByIds(array $ids){
        return $this->role->whereIn('id', $ids)->get();
    }

    /**
     * 获取所有数据
     * @param array $data
     * @return mixed
     */
    public function getAllRoleListByCondition(array $data){
        return $this->role->where($data)->get();
    }

}